
/**
* @Title: ReadWriteComplexTest.java
* @Package com.leetone
* @Description: 【】
* @date 2018年8月29日 下午2:53:52
* @version V1.0
* @Company: 上海未泰信息技术有限公司
* @author:[谭磊][leetone123@163.com]
*/

package com.leetone;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* @ClassName: ReadWriteComplexTest
* @Description: 【复杂读写的例子】
* @date 2018年8月29日 下午2:53:52
* @Company: 上海未泰信息技术有限公司
* @author:[谭磊][leetone123@163.com]
*/

public class ReadWriteComplexTest {
	private final Map<String,Object> map = new HashMap<>();
	private final ReentrantReadWriteLock rwlock = new ReentrantReadWriteLock();
	
	public Object readWrite(String id)
	{
		Object value = null;
		//首先开启读锁，去缓存中去取
		rwlock.readLock().lock();
		try {
			value = map.get(id);
			if(null == value) {
				//如果缓存中没有，就释放读锁，上写锁
				rwlock.readLock().unlock();
				rwlock.writeLock().lock();
				try {
					if(null == value) {
						//此时可以去数据库查找，这里简单处理
						value = "aaa";
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}finally {
					//释放写锁
					rwlock.writeLock().unlock();
				}
				//然后再上读锁
				rwlock.readLock().lock();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			//释放读锁
			rwlock.readLock().unlock();
		}
		return value;
	}
	
	public static void main(String[] args) {
		final ReadWriteComplexTest test = new ReadWriteComplexTest();
		for(int i=0;i<2;i++) {
			new Thread() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					super.run();
					try {
						System.out.println(Thread.currentThread().getName()+"/t get start");
						System.out.println(test.readWrite("aaa"));
						Thread.sleep(1000L);
						System.out.println(Thread.currentThread().getName()+"/t get end");
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}.start();
		}
	}
}
